package com.sinogrand.elevator.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import android.util.Log
import androidx.core.content.ContextCompat
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
 * 定位管理器
 * 负责获取设备当前位置信息
 */
class LocationManager(private val context: Context) {
    
    companion object {
        private const val TAG = "LocationManager"
        private const val MIN_TIME_MS = 10000L // 10秒
        private const val MIN_DISTANCE_M = 10f // 10米
    }
    
    private val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    
    // 位置信息状态流
    private val _currentLocation = MutableStateFlow<Location?>(null)
    val currentLocation: StateFlow<Location?> = _currentLocation.asStateFlow()
    
    // 位置获取状态
    private val _isLocationEnabled = MutableStateFlow(false)
    val isLocationEnabled: StateFlow<Boolean> = _isLocationEnabled.asStateFlow()
    
    // 错误信息
    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()
    
    private val locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            Log.i(TAG, "📍 位置更新: 纬度=${location.latitude}, 经度=${location.longitude}, 精度=${location.accuracy}m")
            _currentLocation.value = location
            _isLocationEnabled.value = true
            _errorMessage.value = null
        }
        
        @Deprecated("Deprecated in Java")
        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
            Log.d(TAG, "📍 定位状态变化: provider=$provider, status=$status")
        }
        
        override fun onProviderEnabled(provider: String) {
            Log.i(TAG, "📍 定位提供者启用: $provider")
        }
        
        override fun onProviderDisabled(provider: String) {
            Log.w(TAG, "📍 定位提供者禁用: $provider")
            _isLocationEnabled.value = false
            _errorMessage.value = "定位服务被禁用"
        }
    }
    
    /**
     * 检查定位权限
     */
    fun hasLocationPermission(): Boolean {
        val fineLocation = ContextCompat.checkSelfPermission(
            context, 
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        
        val coarseLocation = ContextCompat.checkSelfPermission(
            context, 
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        
        Log.d(TAG, "🔐 定位权限检查: 精确位置=$fineLocation, 粗略位置=$coarseLocation")
        return fineLocation || coarseLocation
    }
    
    /**
     * 检查定位服务是否启用
     */
    fun isLocationServiceEnabled(): Boolean {
        val gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        
        Log.d(TAG, "📍 定位服务状态: GPS=$gpsEnabled, 网络=$networkEnabled")
        return gpsEnabled || networkEnabled
    }
    
    /**
     * 开始获取位置
     */
    fun startLocationUpdates() {
        if (!hasLocationPermission()) {
            Log.w(TAG, "⚠️ 没有定位权限，无法获取位置")
            _errorMessage.value = "没有定位权限"
            return
        }
        
        if (!isLocationServiceEnabled()) {
            Log.w(TAG, "⚠️ 定位服务未启用，无法获取位置")
            _errorMessage.value = "定位服务未启用"
            return
        }
        
        try {
            Log.i(TAG, "🚀 开始获取位置信息...")
            
            // 先尝试获取最后已知位置
            val lastKnownLocation = getLastKnownLocation()
            if (lastKnownLocation != null) {
                Log.i(TAG, "📍 获取到最后已知位置: 纬度=${lastKnownLocation.latitude}, 经度=${lastKnownLocation.longitude}")
                _currentLocation.value = lastKnownLocation
                _isLocationEnabled.value = true
            }
            
            // 请求位置更新
            val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
            for (provider in providers) {
                if (locationManager.isProviderEnabled(provider)) {
                    Log.d(TAG, "📍 注册位置监听器: $provider")
                    locationManager.requestLocationUpdates(
                        provider,
                        MIN_TIME_MS,
                        MIN_DISTANCE_M,
                        locationListener,
                        Looper.getMainLooper()
                    )
                }
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "❌ 获取位置失败，权限不足: ${e.message}", e)
            _errorMessage.value = "权限不足，无法获取位置"
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取位置失败: ${e.message}", e)
            _errorMessage.value = "获取位置失败: ${e.message}"
        }
    }
    
    /**
     * 停止位置更新
     */
    fun stopLocationUpdates() {
        try {
            Log.i(TAG, "🛑 停止位置更新")
            locationManager.removeUpdates(locationListener)
            _isLocationEnabled.value = false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 停止位置更新失败: ${e.message}", e)
        }
    }
    
    /**
     * 获取最后已知位置
     */
    private fun getLastKnownLocation(): Location? {
        return try {
            val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER)
            var bestLocation: Location? = null
            
            for (provider in providers) {
                if (locationManager.isProviderEnabled(provider)) {
                    val location = locationManager.getLastKnownLocation(provider)
                    if (location != null) {
                        if (bestLocation == null || location.accuracy < bestLocation.accuracy) {
                            bestLocation = location
                        }
                    }
                }
            }
            
            bestLocation
        } catch (e: SecurityException) {
            Log.e(TAG, "❌ 获取最后已知位置失败，权限不足: ${e.message}", e)
            null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取最后已知位置失败: ${e.message}", e)
            null
        }
    }
    
    /**
     * 获取位置信息字符串
     */
    fun getLocationInfoString(): String {
        val location = _currentLocation.value
        return if (location != null) {
            // "纬度: ${location.latitude}, 经度: ${location.longitude}, 精度: ${location.accuracy}m"
            "纬度: ${String.format("%.6f", location.latitude)}, 经度: ${String.format("%.6f", location.longitude)}, 精度: ${location.accuracy}m"
        } else {
            "位置信息不可用"
        }
    }
    
    /**
     * 获取位置信息详细字符串
     */
    fun getDetailedLocationInfo(): String {
        val location = _currentLocation.value
        return if (location != null) {
            buildString {
                appendLine("📍 当前位置信息:")
                appendLine("  纬度: ${location.latitude}")
                appendLine("  经度: ${location.longitude}")
                appendLine("  精度: ${location.accuracy}m")
                appendLine("  海拔: ${location.altitude}m")
                appendLine("  速度: ${location.speed}m/s")
                appendLine("  方向: ${location.bearing}°")
                appendLine("  时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault()).format(java.util.Date(location.time))}")
                appendLine()
                appendLine("📍 位置信息(6位小数):")
                appendLine("  纬度: ${String.format("%.6f", location.latitude)}")
                appendLine("  经度: ${String.format("%.6f", location.longitude)}")
                appendLine("  精度: ${location.accuracy}m")
            }
        } else {
            "位置信息不可用"
        }
    }
}
